'use strict'

const Controller = require('egg').Controller
const jwt = require('jsonwebtoken')
class UsersController extends Controller {
  async index() {
    const { ctx } = this
    ctx.body = 'hi, egg'
  }
  // code获取接口
  async getCode() {
    const { ctx, app } = this
    try {
      const codeList = await app.mysql.select('code')
      ctx.body = new ctx.SuccessModel(codeList)
    } catch (err) {
      ctx.body = new this.ctx.FailModel(err)
    }
  }

  async loginCode() {
    const { ctx, app } = this
    try {
      // 生成校验码
      const info = ctx.createCode()
      const insertData = await app.mysql.insert('code', { text: info.text })
      // console.log('insertData:', insertData)
      ctx.body = new ctx.SuccessModel({
        insertId: insertData.insertId,
        text: info.text,
        data: info.data,
      })
    } catch (err) {
      ctx.body = new this.ctx.FailModel(err)
    }
  }
  async login() {
    const { ctx, app } = this
    // 1. 拿参数
    const { username, password, text, codeId } = ctx.request.body
    try {
      const codeData = await app.mysql.get('code', { codeId, text })
      if (codeData.length === 0) {
        ctx.body = new ctx.FailModel('验证码有错误，请重新输入')
        return
      }
      const loginData = await app.mysql.get('users', {
        username,
        password: ctx.getPassword(password),
      })
      const token = jwt.sign(
        {
          id: loginData.id,
          username: loginData.username,
        },
        app.config.privateKey,
        { expiresIn: '15s' }
      )
      // 登陆接口中返回用户身份信息
      ctx.body = new ctx.SuccessModel({ token, id: loginData.id })
    } catch (err) {
      ctx.body = new ctx.FailModel('登陆错误，请重新尝试', err)
    }
  }
  async register() {
    const { ctx, app } = this
    // 1. 拿参数
    const { username, password, nickname, gender, avatar } = ctx.request.body
    try {
      const registerData = await app.mysql.insert('users', {
        username,
        password: ctx.getPassword(password),
        nickname,
        gender,
        avatar,
      })
      ctx.body = new ctx.SuccessModel(registerData)
    } catch (err) {
      ctx.body = new ctx.FailModel('注册失败，请重新尝试', err)
    }
  }
  async findUsers() {
    const { app, ctx } = this
    try {
      const { page = 1, size = 5 } = ctx.query
      const { id } = ctx.state.userInfo
      let totalSql = `select count(id) as total from users;`
      let userData
      if (id !== 1) {
        userData = await app.mysql.get('users', { id })
      } else {
        userData = await app.mysql.select('users', {
          // orders: [
          // ['createTime', 'desc'],
          // ['id', 'desc'],
          // ],
          limit: size * 1,
          offset: (page - 1) * size * 1,
        })
      }
      const total = await app.mysql.query(totalSql)
      ctx.body = new ctx.SuccessModel({ total: total[0].total, userData })
    } catch (err) {
      ctx.body = new ctx.FailModel('查询错误', err)
    }
  }
  async usersSearch() {
    const { ctx, app } = this
    const { keywords, page = 1, size = 5 } = ctx.query
    try {
      const sql = `select * from users where username like '%${keywords}%' 
      limit ? offset ?`
      const data = await app.mysql.query(sql, [size * 1, (page - 1) * size * 1])
      ctx.body = new ctx.SuccessModel(data)
    } catch (err) {
      ctx.body = new ctx.FailModel(err)
    }
  }
}

module.exports = UsersController
